package cn.topcodes.tcsf.wechat.service;

import cn.topcode.unicorn.utils.StringUtil;
import cn.topcode.unicorn.wxsdk.WXContext;
import cn.topcode.unicorn.wxsdk.base.Result;
import cn.topcode.unicorn.wxsdk.base.WXResponseCode;
import cn.topcode.unicorn.wxsdk.customerservice.account.AddCustomerServiceAccount;
import cn.topcode.unicorn.wxsdk.customerservice.account.CustomerServiceAccount;
import cn.topcode.unicorn.wxsdk.customerservice.account.CustomerServiceAccountList;
import cn.topcode.unicorn.wxsdk.customerservice.account.ModifyCustomerServiceAccount;
import cn.topcode.unicorn.wxsdk.message.kf.GetAllKfAccountResult;
import cn.topcode.unicorn.wxsdk.message.kf.KfAccount;
import cn.topcodes.tcsf.wechat.domain.entity.WechatKfAccount;
import cn.topcodes.tcsf.admin.commons.generic.GenericService;
import cn.topcodes.tcsf.wechat.domain.entity.WechatMp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 客服账号 服务
 * @author unicorn
 * @date 2017-08-17 17:48:55
 */
@Service
public class WechatKfAccountServiceImpl extends GenericService<WechatKfAccount> implements WechatKfAccountService {

    @Autowired
    private WechatMpService wechatMpService;

    @Override
    public WechatKfAccount findByAccount(String account) {
        if(StringUtil.isBlank(account)) {
            return null;
        }
        Example example = this.buildExample();
        example.or().andEqualTo(WechatKfAccount.FIELD_ACCOUNT, account);
        return this.findOne(example);
    }


    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Long create(WechatKfAccount wechatKfAccount) {
        AddCustomerServiceAccount addCustomerServiceAccount = new AddCustomerServiceAccount();
        addCustomerServiceAccount.setKfAccount(wechatKfAccount.getAccount());
        addCustomerServiceAccount.setNickname(wechatKfAccount.getNickname());
        String mpId = wechatMpService.getCurrentMpId();
        Result result = WXContext.getCustomerServiceInvoker().addCustomerServiceAccount(mpId, addCustomerServiceAccount);
        if(result != null && result.getErrcode() != null && WXResponseCode.CODE_0_SUCCESS == result.getErrcode()) {
            Long id = super.create(wechatKfAccount);
            this.syncAllKfAccount(mpId);
            return id;
        }
        throw new IllegalArgumentException(result.getErrcode() + ":" + result.getErrmsg());
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void update(WechatKfAccount wechatKfAccount) {
        ModifyCustomerServiceAccount modifyCustomerServiceAccount = new ModifyCustomerServiceAccount();
        modifyCustomerServiceAccount.setKfAccount(wechatKfAccount.getAccount());
        modifyCustomerServiceAccount.setNickname(wechatKfAccount.getNickname());
        String mpId = wechatMpService.getMpId(wechatKfAccount.getWechatMpId());
        Result result = WXContext.getCustomerServiceInvoker().modifyCustomerServiceAccount(mpId, modifyCustomerServiceAccount);
        if(result != null && result.getErrcode() != null && WXResponseCode.CODE_0_SUCCESS == result.getErrcode()) {
            WechatKfAccount entity = this.findOne(wechatKfAccount.getId());
            wechatKfAccount.setKfId(entity.getKfId());
            wechatKfAccount.setAccount(entity.getAccount());
            if(StringUtil.isBlank(wechatKfAccount.getHeadImgUrl())) {
                wechatKfAccount.setHeadImgUrl(entity.getHeadImgUrl());
            }
            super.update(wechatKfAccount);
        }
        throw new IllegalArgumentException(result.getErrcode() + ":" + result.getErrmsg());
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public WechatKfAccount delete(Long id) {
        WechatKfAccount wechatKfAccount = this.findOne(id);
        Assert.notNull(wechatKfAccount, "客服账号不存在");
        String mpId = wechatMpService.getMpId(wechatKfAccount.getWechatMpId());
        Result result = WXContext.getCustomerServiceInvoker().deleteCustomerServiceAccount(mpId, wechatKfAccount.getAccount());
        if(result != null && result.getErrcode() != null && WXResponseCode.CODE_0_SUCCESS == result.getErrcode()) {
            return super.delete(id);
        }
        return null;
    }

    /*同步所有客服工号*/
    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void syncAllKfAccount(String mpId) {
        CustomerServiceAccountList rt = WXContext.getCustomerServiceInvoker().getAllCustomerServiceAccount(mpId);
        if(rt != null) {
            List<CustomerServiceAccount> kfAccountList = rt.getKfList();
            if(kfAccountList != null) {
                List<String> accounts = new ArrayList<>();
                for(CustomerServiceAccount account : kfAccountList) {
                    accounts.add(account.getKfAccount());
                    WechatKfAccount wechatKfAccount = this.findByAccount(account.getKfAccount());
                    if(wechatKfAccount == null) {
                        wechatKfAccount = new WechatKfAccount();
                        WechatMp wechatMp = wechatMpService.findWechatMpByMpId(mpId);
                        wechatKfAccount.setWechatMpId(wechatMp.getId());
                    }
                    wechatKfAccount.setKfId(account.getKfId());
                    wechatKfAccount.setAccount(account.getKfAccount());
                    wechatKfAccount.setNickname(account.getKfNick());
                    wechatKfAccount.setHeadImgUrl(account.getKfHeadimgurl());
                    wechatKfAccount.setKfWx(StringUtil.isBlank(account.getKfWx()) ? account.getInviteWx() : account.getKfWx());
                    wechatKfAccount.setInviteStatus(account.getInviteStatus());
                    if(account.getInviteExpireTime() != null) {
                        wechatKfAccount.setInviteExpireTime(new Date(account.getInviteExpireTime()));
                    }
                    if(wechatKfAccount != null) {
                        super.update(wechatKfAccount);
                    }else {
                        super.create(wechatKfAccount);
                    }
                }
                if(!accounts.isEmpty()) {
                    Example example = this.buildExample();
                    example.or().andNotIn(WechatKfAccount.FIELD_ACCOUNT, accounts);
                    this.deleteByExample(example);
                }
            }
            return;
        }
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void syncAllKfAccount() {
        this.syncAllKfAccount(wechatMpService.getDefaultMpId());
    }
}
